<template>
	<view>
		<view class="padding-xl text-center margin-top-xl">
			<view class="logo cu-avatar">
				<open-data type="userAvatarUrl"></open-data>
			</view>
			<view>
				<open-data type="userNickName"></open-data>
			</view>
		</view>
		<view class="line"></view>
		<view class="padding-xl">
			<view><text>申请获取以下权限</text></view>
			<view class="padding-top-sm"><text class="text-gray">获得您的公开信息(昵称,头像等)</text></view>
			<view class="padding-top-xl">
				<button class="cu-btn round block bg-green margin-tb-sm lg" lang="zh_CN" open-type="getUserInfo" @getuserinfo="getUserInfo">授权登录</button>
				<button class="cu-btn round block line-gray margin-tb-sm lg" @click="cancelLogin">取消登录</button>
			</view>
		</view>
	</view>
</template>
<style>
	.logo{width: 250rpx;height: 250rpx;background: transparent;}
</style>
<script>
	import {UserService} from "@/api/UserService.js"
	import {Util} from "@/utils/util.js"
	export default {
		data() {
			return {};
		},
		onLoad() {
			const that =this;
			uni.getSetting({
			   success(res) {
				  if (res.authSetting['scope.userInfo']) {
					  // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
					  uni.getUserInfo({
						lang:"zh_CN",
					  	success:function(e){
							const userInfo=e.userInfo;
							if(userInfo){
								that.userLogin(userInfo).then(result=>{
									if(result){
										uni.navigateBack({});
									}
								});
							}
					  	}
					  });
				  }
			   }
			});
		},
		methods: {
			cancelLogin(){
				uni.switchTab({
					url:"/pages/index/index"
				})
			},
			getUserInfo(e) {
				const userInfo = e.detail.userInfo;
				if (userInfo) {
					this.userLogin(userInfo).then(result=>{
						if(result){
							uni.navigateBack({});
						}
					});
				}else{
					uni.navigateBack({});
				}
			},
			userLogin(userInfo) {
				return new Promise((resolve, reject) => {
					return uni.getProvider({
						service: "oauth",
						success: function(res) {
							const provider = res.provider[0];
							uni.login({
								provider: provider,
								success: function(result) {
									if (result.code) {
										// code换取openId
										UserService.login(result.code,userInfo).then(session=>{
											Util.setCache({key:"session-key",value:session});
											resolve(true);
										});
									}
								},
								fail:function(){
									reject(false);
								}
							});
						}
					});
				});
			}
		}
	}
</script>